package com.baoyouqun.controller.back;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baoyouqun.domain.Query.ReportRecordQueryBack;
import com.baoyouqun.domain.VO.ReportWithDemandVO;
import com.baoyouqun.domain.cmd.BatchUpdateReportStatusCmd;
import com.baoyouqun.service.ReportRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 举报记录管理后台Controller（仅管理员访问）
 * 接口路径统一前缀：/admin/report，与其他后台接口风格保持一致
 */
@Slf4j
@RestController
@RequestMapping("/back/report")
@Api(tags = "后台-举报记录管理接口") // Swagger标签，对齐用户实体类的Swagger注解风格
// @PreAuthorize("hasRole('ADMIN')") // 若用Spring Security，添加管理员权限控制（可选）
public class ReportRecordAdminController {

    @Autowired
    private ReportRecordService reportRecordService;

    // ========================== 分页查询举报记录（带帖子+举报人信息） ==========================
    @ApiOperation(value = "分页查询举报记录", notes = "支持举报类型、处理状态、举报人姓名、时间范围筛选")
    @GetMapping("/page")
    public SingleResponse<IPage<ReportWithDemandVO>> pageReport(
            @ApiParam(value = "举报记录查询条件", required = false)
            @ModelAttribute ReportRecordQueryBack query
    ) {
        try {
            // 调用Service分页查询（自动处理筛选条件：举报人姓名→userIdList→IN查询）
            IPage<ReportWithDemandVO> voPage = reportRecordService.pageAdminReportWithDemand(query);
            return SingleResponse.of(voPage);
        } catch (Exception e) {
            log.error("分页查询举报记录异常", e);
            return SingleResponse.buildFailure("100501", "分页查询失败：" + e.getMessage());
        }
    }

    // ========================== 导出举报记录Excel（Hutool+POI） ==========================
    @ApiOperation(value = "导出举报记录Excel", notes = "按当前筛选条件导出全量数据，支持中文文件名下载")
    @PostMapping("/export")
    public void exportReport(
            @ApiParam(value = "举报记录查询条件", required = false)
            @RequestBody(required = false) ReportRecordQueryBack query,
            @ApiParam(value = "HTTP响应对象（用于输出Excel流）", hidden = true)
            HttpServletResponse response
    ) {
        try {
            // 调用Service导出逻辑（直接写响应流，无返回值）
            reportRecordService.exportAdminReportExcel(query, response);
        } catch (Exception e) {
            log.error("导出举报记录Excel异常", e);
            // 导出异常时向前端返回错误信息（通过响应流写文本，避免页面无响应）
            response.setContentType("text/plain;charset=utf-8");
            try {
                response.getWriter().write("导出失败：" + e.getMessage());
            } catch (Exception ex) {
                log.error("导出异常后写响应流失败", ex);
            }
        }
    }

    // ========================== 批量设置举报记录为“已违规”（帖子下架） ==========================
    @ApiOperation(value = "批量设违规", notes = "更新举报状态为已违规，同步将关联帖子设为下架（status=-1）")
    @PostMapping("/batch-set-violation")
    public Response batchSetViolation(
            @ApiParam(value = "批量操作参数（举报ID列表+处理人ID）", required = true)
            @Valid @RequestBody BatchUpdateReportStatusCmd cmd,
            BindingResult bindingResult
    ) {
        cmd.setHandlerUserId(StpUtil.getLoginIdAsString());
        // 1. 参数校验（捕获@Valid注解的校验错误，如ID列表为空）
        if (bindingResult.hasErrors()) {
            String errorMsg = bindingResult.getFieldErrors().stream()
                    .map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining("；"));
            return Response.buildFailure(errorMsg.split(":", 2)[0], errorMsg.split(":", 2)[1]);
        }

        // 2. 处理结果长度校验（自定义校验逻辑）
        if (!cmd.isValidHandleResult()) {
            return Response.buildFailure(cmd.getHandleResultErrorMsg().split(":", 2)[0],
                    cmd.getHandleResultErrorMsg().split(":", 2)[1]);
        }

        try {
            // 3. 调用Service批量操作（事务保证一致性）
            return reportRecordService.batchSetViolation(cmd);
        } catch (Exception e) {
            log.error("批量设违规异常", e);
            return Response.buildFailure("100502", "批量设违规失败：" + e.getMessage());
        }
    }

    // ========================== 批量设置举报记录为“正常”（帖子恢复） ==========================
    @ApiOperation(value = "批量设正常", notes = "更新举报状态为已驳回，同步将关联帖子设为正常（status=1）")
    @PostMapping("/batch-set-normal")
    public Response batchSetNormal(
            @ApiParam(value = "批量操作参数（举报ID列表+处理人ID）", required = true)
            @Valid @RequestBody BatchUpdateReportStatusCmd cmd,
            BindingResult bindingResult
    ) {
        cmd.setHandlerUserId(StpUtil.getLoginIdAsString());
        // 1. 参数校验（与批量设违规逻辑一致）
        if (bindingResult.hasErrors()) {
            String errorMsg = bindingResult.getFieldErrors().stream()
                    .map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining("；"));
            return Response.buildFailure(errorMsg.split(":", 2)[0], errorMsg.split(":", 2)[1]);
        }

        // 2. 处理结果长度校验
        if (!cmd.isValidHandleResult()) {
            return Response.buildFailure(cmd.getHandleResultErrorMsg().split(":", 2)[0],
                    cmd.getHandleResultErrorMsg().split(":", 2)[1]);
        }

        try {
            // 3. 调用Service批量操作
            return reportRecordService.batchSetNormal(cmd);
        } catch (Exception e) {
            log.error("批量设正常异常", e);
            return Response.buildFailure("100503", "批量设正常失败：" + e.getMessage());
        }
    }

    // ========================== 批量查询举报关联的帖子详情（用于页面展开/收起） ==========================
    @ApiOperation(value = "查询举报关联帖子详情", notes = "传入举报ID列表，返回带帖子完整信息的VO列表")
    @PostMapping("/list-with-demand")
    public SingleResponse<List<ReportWithDemandVO>> listReportWithDemand(
            @ApiParam(value = "举报记录ID列表", required = true)
            @RequestBody List<String> reportIds
    ) {
        try {
            // 校验ID列表非空
            if (CollUtil.isEmpty(reportIds)) {
                return SingleResponse.buildFailure("100301", "举报ID列表不能为空");
            }

            // 调用Service查询关联详情
            List<ReportWithDemandVO> voList = reportRecordService.listReportWithDemand(reportIds);
            return SingleResponse.of(voList);
        } catch (Exception e) {
            log.error("查询举报关联帖子详情异常", e);
            return SingleResponse.buildFailure("100504", "查询详情失败：" + e.getMessage());
        }
    }
}